﻿using Nasty.Core.LoadParams;
using Nasty.Core.Repository;
using Nasty.Core.SuperExtension;
using Nasty.SystemModule.Areas.Department.Model;
using Nasty.SystemModule.Areas.Department.Params;
using Nasty.SystemModule.Department;
using Nasty.SystemModule.User;
using SqlSugar;

namespace Nasty.SystemModule.Department
{
    public interface IDepartmentRepository : IRepository<Nasty.Core.Entity.System.Department>
    {
        public Nasty.Core.Entity.System.Department GetDepartment(string id);

        public ResultData<Nasty.Core.Entity.System.Department> SaveDepartment(DepartmentModel model);

        public ResultData<string> DeleteDepartments(List<string> ids);

        public PageData<Nasty.Core.Entity.System.Department> GetDepartmentPage(GetDepartmentPageParams @params);

        public List<Nasty.Core.Entity.System.Department> GetDepartments(GetDepartmentsParams @params);

        public PageData<DepartmentUserPageModel> GetDepartmentUserPage(GetDepartmentUserPageParams @params);

        public ResultData<string> SaveDepartmentUser(SaveDepartmentUserModel model);

        public ResultData<string> DeleteDepartmentUser(SaveDepartmentUserModel model);

        public ResultData<string> SaveDepartmentUserPost(SaveDepartmentUserPostModel model);
    }

    public class DepartmentRepository : SqlRepository<Nasty.Core.Entity.System.Department>, IDepartmentRepository
    {
        public DepartmentRepository(SqlSugarClient db) : base(db)
        {
            //db.CodeFirst.InitTables(typeof(Department));
            //db.CodeFirst.InitTables(typeof(DepartmentUser));
        }

        public ResultData<string> DeleteDepartments(List<string> ids)
        {
            var result = new ResultData<string>();
            try
            {
                Db.Delete<Nasty.Core.Entity.System.Department>(ids);

                result.IsSuccess = true;
                return result;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                return result;
            }
        }

        public Nasty.Core.Entity.System.Department GetDepartment(string id)
        {
            return this.Db.Queryable<Nasty.Core.Entity.System.Department>().InSingle(id);
        }

        public ResultData<Nasty.Core.Entity.System.Department> SaveDepartment(DepartmentModel model)
        {
            var result = new ResultData<Nasty.Core.Entity.System.Department>();
            try
            {
                var data = Db.Save<Nasty.Core.Entity.System.Department>(model);
                result.Data = data;
                result.IsSuccess = true;
                return result;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                return result;
            }
        }

        public PageData<Nasty.Core.Entity.System.Department> GetDepartmentPage(GetDepartmentPageParams @params)
        {
            int totalPage = 0;
            int total = 0;
            var pageData = new PageData<Nasty.Core.Entity.System.Department>();

            var _SQLExpress = Db.Queryable<Nasty.Core.Entity.System.Department>();

            if (!string.IsNullOrEmpty(@params.Name)) _SQLExpress.Where((t) => t.Name.Contains(@params.Name));
            if (!string.IsNullOrEmpty(@params.Code)) _SQLExpress.Where((t) => t.Code.Contains(@params.Code));
            _SQLExpress = _SQLExpress.OrderBy((t) => t.CreateTime, OrderByType.Desc);

            var data = _SQLExpress.ToPageList(@params.Current, @params.PageSize, ref total, ref totalPage);

            pageData.Total = total;
            pageData.TotalPage = totalPage;
            pageData.Data = data;

            pageData.Current = @params.Current;
            pageData.PageSize = @params.PageSize;
            return pageData;
        }


        public List<Nasty.Core.Entity.System.Department> GetDepartments(GetDepartmentsParams @params)
        {
            var _SQLExpress = Db.Queryable<Nasty.Core.Entity.System.Department>();
            if (!string.IsNullOrEmpty(@params.ParentId))
                _SQLExpress.Where((t) => t.ParentId == @params.ParentId);
            else
                _SQLExpress.Where((t) => string.IsNullOrEmpty(t.ParentId));

            return _SQLExpress.ToList();
        }

        public PageData<DepartmentUserPageModel> GetDepartmentUserPage(GetDepartmentUserPageParams @params)
        {
            int totalPage = 0;
            int total = 0;
            var pageData = new PageData<DepartmentUserPageModel>();

            var _SQLExpress = Db.Queryable<Nasty.Core.Entity.System.DepartmentUser>()
                .InnerJoin<Nasty.Core.Entity.System.User>((du, u) => du.UserId == u.Id)
                .InnerJoin<Nasty.Core.Entity.System.Department>((du, u, d) => du.DepartmentId == d.Id);
            var sql = _SQLExpress.Select((du, u, d) => new DepartmentUserPageModel()
            {
                Id = u.Id,
                Name = u.Name,
                Avatar = u.Avatar,
                Account = u.Account,
                Department = d.Name,
                DepartmentId = d.Id,
                SerialNumber = d.SerialNumber ?? string.Empty,
                Post = du.Post,
                PostId = du.PostId,
                IsMaster = du.IsMaster,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUser = u.CreateUser,
                UpdateUser = u.UpdateUser,
                UpdateUserId = u.UpdateUserId,
                CreateUserId = u.CreateUserId,
                CreateDept = u.CreateDept,
                CreateDeptId = u.CreateDeptId,
                UpdateDept = u.UpdateDept,
                UpdateDeptId = u.UpdateDeptId
            }).MergeTable();

            if (!string.IsNullOrEmpty(@params.DepartmentId)) sql = sql.Where((u) => u.DepartmentId == @params.DepartmentId);
            if (!string.IsNullOrEmpty(@params.SerialNumber)) sql = sql.Where((u) => u.SerialNumber.Contains(@params.SerialNumber));

            if (!string.IsNullOrEmpty(@params.Name)) sql.Where((u) => u.Name.Contains(@params.Name));
            if (!string.IsNullOrEmpty(@params.Account)) sql.Where((u) => u.Account.Contains(@params.Account));
            sql = sql.OrderBy((t) => t.CreateTime, OrderByType.Desc);

            var data = sql.ToPageList(@params.Current, @params.PageSize, ref total, ref totalPage);

            pageData.Total = total;
            pageData.TotalPage = totalPage;
            pageData.Data = data;

            pageData.Current = @params.Current;
            pageData.PageSize = @params.PageSize;
            return pageData;
        }

        public ResultData<string> SaveDepartmentUser(SaveDepartmentUserModel model)
        {
            var result = new ResultData<string>();
            try
            {

                var dept = Db.Queryable<Nasty.Core.Entity.System.Department>().Includes((t) => t.Users).InSingle(model.DepartmentId);
                if (dept == null)
                {
                    result.IsSuccess = false;
                    result.Message = "部门不存在!";
                    return result;
                }

                var post = Db.Queryable<Nasty.Core.Entity.System.Post>().InSingle(model.PostId);
                foreach (var userId in model.UserIds)
                {
                    var deptUser = Db.Queryable<Nasty.Core.Entity.System.DepartmentUser>().Where((t) => t.DepartmentId == model.DepartmentId && t.UserId == userId).First();
                    if (deptUser == null)
                    {
                        var user = Db.Queryable<Nasty.Core.Entity.System.User>().InSingle(userId);
                        if (user != null)
                        {
                            deptUser = new Nasty.Core.Entity.System.DepartmentUser()
                            {
                                UserId = user.Id,
                                DepartmentId = model.DepartmentId,
                                IsMaster = false,
                                Post = post?.Name,
                                PostId = post?.Id,
                            };

                            Db.Insertable(deptUser).ExecuteCommand();
                        }
                    }
                }

                result.IsSuccess = true;
                return result;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                return result;
            }
        }

        public ResultData<string> DeleteDepartmentUser(SaveDepartmentUserModel model)
        {
            var result = new ResultData<string>();
            try
            {

                var dept = Db.Queryable<Nasty.Core.Entity.System.Department>().Includes((t) => t.Users).InSingle(model.DepartmentId);
                if (dept == null)
                {
                    result.IsSuccess = false;
                    result.Message = "部门不存在!";
                    return result;
                }

                foreach (var userId in model.UserIds)
                {
                    Db.Deleteable<Nasty.Core.Entity.System.DepartmentUser>().Where((t) => t.DepartmentId == model.DepartmentId && t.UserId == userId).ExecuteCommand();
                }

                result.IsSuccess = true;
                return result;
            }
            catch (Exception ex)
            {
                result.IsSuccess = false;
                result.Message = ex.Message;
                return result;
            }
        }

        public ResultData<string> SaveDepartmentUserPost(SaveDepartmentUserPostModel model)
        {
            var result = new ResultData<string>();
            try
            {
                Db.BeginTran();
                var deptUser = Db.Queryable<Nasty.Core.Entity.System.DepartmentUser>().Where((t) => t.DepartmentId == model.DepartmentId && t.UserId == model.UserId).First();
                if (deptUser == null)
                {
                    result.IsSuccess = false;
                    result.Message = "部门成员不存在!";
                    return result;
                }

                var post = Db.Queryable<Nasty.Core.Entity.System.Post>().InSingle(model.PostId);
                if (post == null)
                {
                    result.IsSuccess = false;
                    result.Message = "岗位不存在!";
                    return result;
                }

                deptUser.PostId = model.PostId;
                deptUser.Post = post.Name;

                deptUser.IsMaster = model.IsMaster ?? false;

                Db.Updateable(deptUser).ExecuteCommand();

                //如果设置了主要责任部门，则将其他部门的主要责任部门设置为false
                if (model.IsMaster == true)
                {
                    Db.Updateable<Nasty.Core.Entity.System.DepartmentUser>()
                        .SetColumns((t) => new Nasty.Core.Entity.System.DepartmentUser() { IsMaster = false })
                        .Where((t) => t.DepartmentId != model.DepartmentId && t.UserId == model.UserId)
                        .ExecuteCommand();
                }

                Db.CommitTran();
                result.IsSuccess = true;
                return result;
            }
            catch (Exception ex)
            {
                Db.RollbackTran();
                result.IsSuccess = false;
                result.Message = ex.Message;
                return result;
            }
        }
    }
}
